package com.flute.haflute.net.messaging;

import java.util.Map;

import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.flute.haflute.agent.topo.ClusterMessageListener;
import com.flute.haflute.agent.topo.DefaultClusterStateListener;

/**
 * Haflute集群的消息集中处理器，所有的异步消息都在此预处理
 */
public class MessageHandlerInMina extends IoHandlerAdapter implements IoHandler {

	private static Logger logger = LoggerFactory
			.getLogger(MessageHandlerInMina.class);

	private Map<Message.Verb, ClusterMessageListener> messageSubscribes;

	private ClusterMessageListener defaultMessageSubscribe;

	public MessageHandlerInMina(
			Map<Message.Verb, ClusterMessageListener> messageSubscribes) {
		this.messageSubscribes = messageSubscribes;
		this.defaultMessageSubscribe = new DefaultClusterStateListener();
	}

	/*
	 * @see
	 * org.apache.mina.core.service.IoHandler#exceptionCaught(org.apache.mina
	 * .core.session.IoSession, java.lang.Throwable)
	 */
	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		logger.info("error in MINA udp communication: ", cause);
	}

	/*
	 * @see
	 * org.apache.mina.core.service.IoHandler#messageReceived(org.apache.mina
	 * .core.session.IoSession, java.lang.Object)
	 */
	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		Message realMessage = (Message) message;
		ClusterMessageListener listener = messageSubscribes.get(realMessage
				.getVerb());
		if (listener == null) {
			listener = defaultMessageSubscribe;
		}
		listener.asyncHandle(realMessage, session);
	}

}
